package com.dtcnet.skmvp.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtcnet.skmvp.utils.MMKVUtils;

import java.lang.reflect.Field;

/**
 * @author snoopy
 */
public class BaseBean {

    public boolean saveAsJson() {
//        String json = new Gson().toJson(this);
//        return MMKVUtils.getInstance().saveString(getKey(), new Gson().toJson(this));
        return MMKVUtils.getInstance().saveString(getKey(), JSON.toJSONString(this));
    }

    public static <E extends BaseBean> E loadBean(Class<? extends BaseBean> c) {

        try {
            BaseBean obj = c.newInstance();

            String data = MMKVUtils.getInstance().getString(obj.getKey(), null);

            if (data != null) {
//                ResponseEntityToModule.parseJsonToModule(data,obj.getClass())
//                obj.copy(new Gson().fromJson(data, obj.getClass()));
                obj.copy(JSONObject.parseObject(data, obj.getClass()));
                return (E) obj;
            }

        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }

        return null;
    }

    private String getKey() {
        return getClass().getName();
    }

    public void copy(Object object) {
        Field[] tFields = this.getClass().getDeclaredFields();
        Field[] oFields = object.getClass().getDeclaredFields();

        for (int i = 0; i < tFields.length; i++) {
            Field tF = tFields[i];
            Field oF = oFields[i];
            tF.setAccessible(true);
            oF.setAccessible(true);
            try {

                tF.set(this, oF.get(object));

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
